/**
 * Created by somnus on 16/7/25.
 */
package com.dzpk.facadeserver.manager;

import java.util.*;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * 游戏服务器manager
 */
public class GameServerManager {

    private static GameServerManager gameServerManager = new GameServerManager();

    private GameServerManager(){
        serverUsers.put("localhost:36999", new ArrayList<Long>());
    }

    public static GameServerManager getInstance(){
        return gameServerManager;
    }

    private ReentrantReadWriteLock lock = new ReentrantReadWriteLock();

    private ReentrantReadWriteLock.ReadLock readLock = lock.readLock();

    private ReentrantReadWriteLock.WriteLock writeLock = lock.writeLock();

    private Map<Long, Token> userToken = new HashMap<>();

    // <ip:port, userIds>
    private Map<String, List<Long>> serverUsers = new HashMap<>();

    private String getServer(){
        Iterator<String> ips = serverUsers.keySet().iterator();
        if(ips.hasNext()){
            return ips.next();
        }
        return null;
    }

    public Token getServer(long userId){
        try {
            writeLock.lock();
            Token token = userToken.get(userId);
            if(token == null){
                String serverInfo = getServer();
                if (serverInfo == null) {
                    token = new Token(-999);
                }else{
                    token = new Token(userId,serverInfo);
                }
            }else{
                token = new Token(-100);
            }
            return token;
        }finally {
            writeLock.unlock();
        }

    }

}
